/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.frontend.server;

import com.google.appengine.api.datastore.Text;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import za.org.foobar.famon.frontend.client.FamonException;
import za.org.foobar.famon.model.Page;
import za.org.foobar.famon.util.DB;

import java.util.List;


/**
 *
 */
public class PageEditorLogic {
    private final Log log = LogFactory.getLog(getClass());

    private static PageEditorLogic instance;
    public static PageEditorLogic get() {
        return instance == null ? instance = new PageEditorLogic() : instance;
    }
    
    public PageEditorLogic() {
        log.debug("Creating PageEditorLogic");
    }

    public List<String> getPageList() {
        return DB.createDBQuery(Page.class, "name")
                .addOrderBy("name")
                .getResultList(String.class);
    }

    public void newPage(String name) throws FamonException {
        DB.begin();
        DB.persist(new Page(name));
        DB.commit();
    }

    public String getPageXml(String name) throws FamonException {
        Page page = DB.findByName(Page.class, name);
        if (page == null) {
            return null;
        }
        Text contents = page.getContents();
        if (contents == null) {
            return null;
        }
        return contents.getValue();
    }

    public void setPageXml(String name, String value) throws FamonException {
        DB.begin();
        try {
            Page page = DB.findByName(Page.class, name);
            if (page == null) {
                page = new Page(name);
                DB.persist(page);
            }
            page.setContents(new Text(value));
            DB.commit();
        } finally {
            DB.rollbackOpenTransaction();
        }
    }

}
